package com.todaynews.api;

import com.google.gson.GsonBuilder;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.todaynews.frame.common.CommonConfig;
import com.todaynews.frame.logger.Logger;
import com.todaynews.utils.Constants;
import com.todaynews.utils.file.FileUtils;
import java.io.File;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 */

public class ApiRetrofit {

    private static ApiRetrofit apiRetrofit;
    private final Retrofit retrofit;
    private OkHttpClient client;
    private ApiService apiService;

    public static ApiRetrofit getInstance() {
        if (apiRetrofit == null) {
            synchronized (Object.class) {
                if (apiRetrofit == null) {
                    apiRetrofit = new ApiRetrofit();
                }
            }
        }
        return apiRetrofit;
    }

    public ApiRetrofit() {

        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        client = okHttpClientBuilder
                .addInterceptor(headerInterceptor)//添加头部信息拦截器
                .addInterceptor(logInterceptor)//添加log拦截器
                .cache(getCache())
                .connectTimeout(CommonConfig.CONNECTIONTIME, TimeUnit.SECONDS)//连接超时
                .readTimeout(CommonConfig.READTIME, TimeUnit.SECONDS)//读取超时
                .writeTimeout(CommonConfig.WRITETIME, TimeUnit.SECONDS)//写入超时
                .retryOnConnectionFailure(false)
                .build();

        //1:创建Retrofit对象
         retrofit = new Retrofit.Builder()
                 .baseUrl(Constants.BASE_SERVER_URL)
                 .addConverterFactory(ScalarsConverterFactory.create())
                 //.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                 .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava//支持RxJava
                 .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                 .client(client)
                 .build();
        //步骤2:创建 网络请求接口的实例
         apiService = retrofit.create(ApiService.class);
    }

    public ApiService getApiService() {
        return apiService;
    }

    /**增加头部信息的拦截器*/
    private Interceptor headerInterceptor = chain -> {
        Request.Builder builder = chain.request().newBuilder();
        builder.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.108 Safari/537.36 2345Explorer/8.0.0.13547");
        builder.addHeader("Cache-Control", "max-age=0");
        builder.addHeader("Upgrade-Insecure-Requests", "1");
        builder.addHeader("X-Requested-With", "XMLHttpRequest");
        builder.addHeader("Cookie", "uuid=\"w:f2e0e469165542f8a3960f67cb354026\"; __tasessionId=4p6q77g6q1479458262778; csrftoken=7de2dd812d513441f85cf8272f015ce5; tt_webid=36385357187");
        return chain.proceed(builder.build());
    };

    /**请求访问quest和response拦截器*/
    private Interceptor logInterceptor = chain -> {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        okhttp3.Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        Logger.e("----------Request Start----------------");
        Logger.e("| " + request.toString());
        Logger.json("| Response:" + content);
        Logger.e("----------Request End:" + duration + "毫秒----------");
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    };

    /**
     * okhttp缓存
     */
    private Cache getCache(){
        // 缓存目录
        File httpCacheDirectory = new File(FileUtils.getInstance().getRootDirectory(),CommonConfig.CACHE_SP_NAME);
        Cache cache = new Cache(httpCacheDirectory, CommonConfig.OKHTTP_CACHE_SIZE);
        return cache;
    }
}
